package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override//新增分类
    public void save(Category category) {
        //1.补全信息
        //1-1  id
        long id = IdUtil.getSnowflake(1, 1).nextId();
        //存入id
        category.setId(id);
        //1-2创建 更新人
        // category.setUpdateUser(1L);//TODO
        // category.setCreateUser(1L);
        // //1-3创建时间更新时间
        // category.setUpdateTime(new Date());
        // category.setCreateTime(new Date());
        //调用mapper新增
        categoryMapper.insert(category);
    }

    // 分类修改
    @Override
    public void update(Category category) {
        // 1.补全信息
        //category.setUpdateUser(1L); // TODO暂时写死
        //category.setUpdateTime(new Date());
        // 2.调用mapper修改
        categoryMapper.updateById(category);
        System.out.println("++++++++++++++++++++++++++++++");
        System.out.println(category.toString());

    }

    //删除

    //*@Override
    public void selete(Long id) {
        //根据分类id查询菜品数量
        Integer dis = categoryMapper.countDishByCategoryId(id);
        if (dis > 0) {
            //return ResultInfo.error("该分类下有菜品");
            throw new CustomException("该分类下有菜品");
        }
        //根据分类id（查询套餐数量
        Integer tid=categoryMapper.taocanId(id);
        if (tid > 0) {
            // return ResultInfo.error("改套餐下有套餐");
            throw new CustomException("该分类下有套餐，不允许删除");
        }
        //根据id分类
        categoryMapper.delete(id);

    }
    //新增菜品，套餐时分类信息
    @Override
    public List<Category> findById(Integer type) {
        //构建条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType, type);//根据类型 type=1
        qw.orderByAsc(Category::getSort); // 分类升序order by sort asc
        //调用mapper返回并返回
        return categoryMapper.selectList(qw);

    }




}
